import itertools
import pandas as pd
import tensorflow as tf

tf.logging.set_verbosity(tf.logging.INFO)  # 设置日志级别

COLUMNS = ["crim", "zn", "indus", "nox", "rm", "age", "dis", "tax", "ptratio", "medv"]  # 所有可用列
FEATURES = ["crim", "zn", "indus", "nox", "rm", "age", "dis", "tax", "ptratio"]  # 特征值列
LABEL = "medv"  # 目标值列


def input_fn(data_set):
    """
    模型参数输入方法
    :param data_set: pandas对象
    :return:
    """
    feature_cols = {k: tf.constant(data_set[k].values) for k in FEATURES}
    labels = tf.constant(data_set[LABEL].values)
    return feature_cols, labels


def main(unused_argv):
    """
    tf.app.run()运行的默认方法体
    :param unused_argv: 使用tf.app.run()运行时本参数用于接收外部参数
    :return:
    """
    # 读取数据
    training_set = pd.read_csv(
        "../data/resource/boston/boston_train.csv",
        skipinitialspace=True,
        skiprows=1,
        names=COLUMNS  # 自定义列名
    )  # 训练数据
    test_set = pd.read_csv(
        "../data/resource/boston/boston_test.csv",
        skipinitialspace=True,
        skiprows=1,
        names=COLUMNS
    )  # 测试数据
    prediction_set = pd.read_csv(
        "../data/resource/boston/boston_predict.csv",
        skipinitialspace=True,
        skiprows=1,
        names=COLUMNS
    )  # 预测数据

    feature_cols = [tf.contrib.layers.real_valued_column(k) for k in FEATURES]  # 设置特征列集合
    regressor = tf.contrib.learn.DNNRegressor(
        feature_columns=feature_cols,  # 特征列集合
        hidden_units=[10, 10],  # 2个隐藏层，每个隐藏层包含10个神经元。
        model_dir="../data/model/l025_boston"
    )  # 创建神经网络回归模型

    # 训练模型
    regressor.fit(input_fn=lambda: input_fn(training_set), steps=5000)  # 注意使用lambda语法，而非直接调用input_fn(training_set)

    # 测试模型
    ev = regressor.evaluate(input_fn=lambda: input_fn(test_set), steps=1)
    print(ev)
    loss_score = ev["loss"]
    print("Loss: {0:f}".format(loss_score))

    # 预测模型(使用模型)
    y = regressor.predict(input_fn=lambda: input_fn(prediction_set))
    predictions = list(itertools.islice(y, 6))  # 从迭代器y中返回6条记录
    print("Predictions: {}".format(str(predictions)))

if __name__ == "__main__":
    tf.app.run()  # 将调用本文件的main方法
